
/**
 * removes all the empty characters form the begining and the end of the sring str
 * @param {string} str - string to process
 */
function ListonicTrim(str) {
	var trimmed = str

	if(trimmed) {
		trimmed = trimmed.replace(/^\s+|\s+$/g, '');
	}

	return trimmed;
}

/**
 * estimatest number of words in the string
 * @param {string} str
 */
function ListonicWC(str) {
	var wcregex = /(^|\s)[^\s]+?(?=\s|$)/ig;

	var matches = str.match(wcregex);

	if(matches) {
		return matches.length;
	} else {
		return 0;
	}
}

/**
 * BlogProcessor - used to process blog entres searching for specific DOM tree patterns indicating list of ingredient.
 * Once found, ingredients are extracted and Listonic Button is generated next to them.
 */
function BlogProcessor(type) {
	this.type = type;
	
	this.isIndividualView = false;
	//okrela czy jestemy w widoku pojedynczego wpisu czy ca³ociowym
	//ma znaczenie przy blox.pl

	this.widgetInfoUrl = "http://listonic.pl/c/cms/blogwidget_about";

	this.buttonsInfoUrl = "http://na1000sposobow.pl/jak-to-dziala/";
	
	
	this.language = typeof listonic_language=="string"?listonic_language:"pl_PL";
	this.language = this.language.toLowerCase();
	
	
	//defines language specific resource eg. texts, images, urls, parameters steering other mechanisms 
	this.resources = {
		pl_PL : {
			themePrefix : "",
			themeSuffix : "",
			howItWorksText : "Jak to dzia³a?",
			howItWorksUrl : "http://na1000sposobow.pl/jak-to-dziala/",
			iWantButtonText : "Chcê taki przycisk",
			iWantButtonUrl : "http://listonic.pl/c/cms/blogwidget_about"
		},
		en_US : {
			themePrefix : "",
			themeSuffix : "_en",
			howItWorksText : "How it works?",
			howItWorksUrl : "http://na1000sposobow.pl/jak-to-dziala/",
			iWantButtonText : "I want button.",
			iWantButtonUrl : "http://listonic.pl/c/cms/blogwidget_about"
			
		}
	}; 
		
	this.buttonUrl = "http://buttons.listonic.pl/v1/button.js";

	this.iframeclass = "ekcal_ifrm";
	this.iframeusedclass = "listonic_ifrm_used";

	this.firstOnly = null;
	this.firstOnlyDefined = false;

	this.minCount = 3;
	this.minCountDefined = true;

	this.includeTags = null;
	this.includeTagsDefined = false;

	this.excludeTags = null;
	this.excludeTagsDefined = false;

	this.iframeWidth = null;
	this.iframeWidthDefined = false;

	this.sidebarVisible = true;

	this.listonicButtonIndex = 0;

	this.genericVars = new Array();
	
	/**
	 * functions
	 */
	this.getBlogEntries = null;
	this.checkIfInclude = null;
	this.getEntryContent = null;
	this.getEntryTitle = null;
	this.getEntryUrl = null;
	
	this.Init = function() {
		console.log('init start 3')
		//alert('init start 3');
		
		this.initType();
				
		var do_turnOff = false;
		if(this.isdefined('listonic_turnOff')) {
			do_turnOff = Boolean(listonic_turnOff);
		}

		if(!do_turnOff) {
			if(this.type) {
				if(this.type == "blox") {
					this.initBlox();
				} else if(this.type == "bloog") {
					this.initBloog();
				} else if(this.type == "blogger") {
					this.initBlogger();
				} else if(this.type == "generic") {
					this.initGeneric();
				}
			}
		}
		//alert('init end:'+this.type);
	}
	
	this.initType = function() {
		if(this.isdefined('listonic_bw_type')) {
			this.type = listonic_bw_type;
			return;
			//TODO: make it more stupid proof
			//validate choice
		}

		var domain = window.location.hostname;

		if(domain.match(/.*blogspot.com$/ig)) {
			this.type = "blogger"
		} else if(domain.match(/.*blox.pl$/ig)) {
			this.type = "blox";
		} else if(domain.match(/.*bloog.pl$/ig)) {
			this.type = "bloog";
		}
	};
	
	this.initBlogger = function() {
		this.getBlogEntries = this.getBlogEntriesBlogger;
		this.checkIfInclude = this.checkIfIncludeBlogger;
		this.getEntryContent = this.getEntryContentBlogger;
		this.getEntryTitle = this.getEntryTitleBlogger;
		this.getEntryUrl = this.getEntryUrlBlogger;
	};
	
	this.getBlogEntriesBlogger = function() {
		var contentDiv = document.getElementById("Blog1");

		var entries = this.getElementsByClassNameL("post", contentDiv, "div");

		return entries;
	};
	
	this.getEntryContentBlogger = function(entry) {
		var result = null;
		if(entry) {
			result = this.getElementsByClassNameL("post-body", entry, "div");
		}

		return result;
	};
	
	this.getEntryTitleBlogger = function(entry) {
		var result = null;

		if(entry) {
			var titleElem = this.getElementsByClassNameL("post-title", entry, "h3");

			if(titleElem && titleElem.length > 0) {
				result = this.parseHTMLForEscapedText(titleElem[0]);
			}

		}

		return result;
	};
	
	this.getEntryUrlBlogger = function(entry) {
		var result = null;

		if(entry) {
			var titleElem = this.getElementsByClassNameL("post-title", entry, "h3");

			if(titleElem && titleElem.length > 0) {

				var alink = titleElem[0].getElementsByTagName("a");

				if(alink && alink.length > 0) {
					result = alink[0].href;
				}
			} else {// nie podano tytu³u
				result = this.getEntryUrlFooterBlogger(entry);
			}

		}

		return result;
	};
	
	this.getEntryUrlFooterBlogger = function(entry) {
		var result = null;
		if(entry) {
			var footer = this.getElementsByClassNameL("post-footer", entry, "div");

			if(footer && footer.length > 0) {
				var timestamp = this.getElementsByClassNameL("post-timestamp", footer[footer.length - 1], "span");

				if(timestamp && timestamp.length > 0) {
					var alink = timestamp[0].getElementsByTagName("a");

					if(alink && alink.length > 0) {
						result = alink[0].href;
					}

				}
			}

		}
		return result;
	};
	
	this.parseHTMLForEscapedText = function(element) {
		var result = "";

		if(element) {
			if(this.hasInnerText) {
				result = element.innerText;
			} else {
				result = element.textContent;
			}
		}

		if(result) {
			result = this.escapeApostrophe(result);
		}

		return result;
	};
	
	this.escapeApostrophe = function(str) {
		var result = str.replace(/\'/gi, "\\'");
		return result;
	};
	
	this.checkIfIncludeBlogger = function(entry) {
		var result = true;

		//sprawdÅº czy nie istnieje juÅ¼ listonic button
		if(this.hasListonicButton(entry)) {
			return false;
		}

		/*var tags = this.getTagsBlogger(entry);

		if(this.excludeTagsDefined) {//if exclude tags are defined to not include the button
			var exclude = this.tagsContains(tags, this.excludeTags);

			if(exclude) {
				return false;
			}
		}

		if(this.includeTagsDefined) {// jeÅli sÄ tagi
			var include = this.tagsContains(tags, this.includeTags);
			if(include) {

			} else {
				return false;
			}

		}
*/
		return result;
	};
	
	this.hasListonicButton = function(entry) {
		if(entry) {
			var buttons = this.getElementsByClassNameL(this.iframeclass, entry, "iframe");
			if(buttons && buttons.length > 0) {
				return true;
			}
			buttons = this.getElementsByClassNameL(this.iframeusedclass, entry, "iframe");
			if(buttons && buttons.length > 0) {
				return true;
			}
		}
		return false;
	};
	
	/**
	 * 
	 */
	this.process = function() {
		console.log('process')
		if(this.getBlogEntries) {
			var entries = this.getBlogEntries();
			console.log('entries'+entries.length)
			this.processBlogEntries(entries);
		}
	};
	
	this.processBlogEntries = function(entries) {

		if(entries) {
			if(entries.length > 0) {
				//console.log(entries.length);

				for(var i = 0; i < entries.length; i++) {//TODO: fix
					console.log(entries[i]);

					//check if suitable for processing
					if(this.checkIfInclude(entries[i])) {

						this.processBlogEntry(entries[i]);
					}

				}
			}
		}
	};

	this.processBlogEntry = function(entry) {
		//console.log(entry);
  
		var entrycontents = this.getEntryContent(entry);

		console.log(entrycontents);

		if(entrycontents && entrycontents.length > 0) {

			var entrycontent = entrycontents[0];

			var entrytitle = this.getEntryTitle(entry)
			entrytitle = ListonicTrim(entrytitle);
			
			var entryurl = this.getEntryUrl(entry);
			console.log("entrytitle"+entrytitle);
			
			var imgs = entrycontent.getElementsByTagName("img");
			if (imgs && imgs.length > 0) {
				this.generateEkcalFrame(imgs[0], entrytitle, entryurl);
			}
		}
		
	};
	
	this.generateEkcalFrame = function(imgElement, title, url) {
		//console.log("buttons");
		//console.log(items);
		//console.log(ulElement);
  alert('entry');
			var div = document.createElement('div');
			var iframe = document.createElement('iframe');
			iframe.setAttribute('class', this.iframeclass)
			iframe.setAttribute('height', '50px')
			iframe.setAttribute('width', '150px')
			iframe.setAttribute('src', 'http://ekcal.com/test/test/xxx')
			div.appendChild(iframe);
			this.insertAfter(imgElement.parentNode, div);
		
		
	};
	
	this.insertAfter = function(currentElement, newElement) {

		var nextObj = currentElement.nextSibling;

		if(nextObj) {
			currentElement.parentNode.insertBefore(newElement, nextObj);
		} else {
			currentElement.parentNode.appendChild(newElement);
		}

	};
	
	this.getElementsByClassNameL = function(searchClass, node, tag) {

		var classElements = new Array();
		if(node == null)
			node = document;

		if(searchClass == null) {
			if(tag != null)
				var result = node.getElementsByTagName(tag);

			return result;
		}

		if(tag == null)
			tag = '*';

		var els = node.getElementsByTagName(tag);
		var elsLen = els.length;
		var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
		for( i = 0, j = 0; i < elsLen; i++) {
			if(pattern.test(els[i].className)) {
				classElements[j] = els[i];
				j++;
			}
		}
		return classElements;
	};

	this.isdefined = function(variable) {
		return ( typeof (window[variable]) == "undefined") ? false : true;
	};
	
}

var ListonicBlogWidgetInstance = new BlogProcessor("blogger");
ListonicBlogWidgetInstance.Init();
ListonicBlogWidgetInstance.process();

var ListonicEventDocumentReady = (function(){    

    var readyList,
        DOMContentLoaded,
        class2type = {};
        class2type["[object Boolean]"] = "boolean";
        class2type["[object Number]"] = "number";
        class2type["[object String]"] = "string";
        class2type["[object Function]"] = "function";
        class2type["[object Array]"] = "array";
        class2type["[object Date]"] = "date";
        class2type["[object RegExp]"] = "regexp";
        class2type["[object Object]"] = "object";

    var ReadyObj = {
        // Is the DOM ready to be used? Set to true once it occurs.
        isReady: false,
        // A counter to track how many items to wait for before
        // the ready event fires. See #6781
        readyWait: 1,
        // Hold (or release) the ready event
        holdReady: function( hold ) {
            if ( hold ) {
                ReadyObj.readyWait++;
            } else {
                ReadyObj.ready( true );
            }
        },
        // Handle when the DOM is ready
        ready: function( wait ) {
            // Either a released hold or an DOMready/load event and not yet ready
            if ( (wait === true && !--ReadyObj.readyWait) || (wait !== true && !ReadyObj.isReady) ) {
                // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
                if ( !document.body ) {
                    return setTimeout( ReadyObj.ready, 1 );
                }

                // Remember that the DOM is ready
                ReadyObj.isReady = true;
                // If a normal DOM Ready event fired, decrement, and wait if need be
                if ( wait !== true && --ReadyObj.readyWait > 0 ) {
                    return;
                }
                // If there are functions bound, to execute
                readyList.resolveWith( document, [ ReadyObj ] );

                // Trigger any bound ready events
                //if ( ReadyObj.fn.trigger ) {
                //  ReadyObj( document ).trigger( "ready" ).unbind( "ready" );
                //}
            }
        },
        bindReady: function() {
            if ( readyList ) {
                return;
            }
            readyList = ReadyObj._Deferred();

            // Catch cases where $(document).ready() is called after the
            // browser event has already occurred.
            if ( document.readyState === "complete" ) {
                // Handle it asynchronously to allow scripts the opportunity to delay ready
                return setTimeout( ReadyObj.ready, 1 );
            }

            // Mozilla, Opera and webkit nightlies currently support this event
            if ( document.addEventListener ) {
                // Use the handy event callback
                document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
                // A fallback to window.onload, that will always work
                window.addEventListener( "load", ReadyObj.ready, false );

            // If IE event model is used
            } else if ( document.attachEvent ) {
                // ensure firing before onload,
                // maybe late but safe also for iframes
                document.attachEvent( "onreadystatechange", DOMContentLoaded );

                // A fallback to window.onload, that will always work
                window.attachEvent( "onload", ReadyObj.ready );

                // If IE and not a frame
                // continually check to see if the document is ready
                var toplevel = false;

                try {
                    toplevel = window.frameElement == null;
                } catch(e) {}

                if ( document.documentElement.doScroll && toplevel ) {
                    doScrollCheck();
                }
            }
        },
        _Deferred: function() {
            var // callbacks list
                callbacks = [],
                // stored [ context , args ]
                fired,
                // to avoid firing when already doing so
                firing,
                // flag to know if the deferred has been cancelled
                cancelled,
                // the deferred itself
                deferred  = {

                    // done( f1, f2, ...)
                    done: function() {
                        if ( !cancelled ) {
                            var args = arguments,
                                i,
                                length,
                                elem,
                                type,
                                _fired;
                            if ( fired ) {
                                _fired = fired;
                                fired = 0;
                            }
                            for ( i = 0, length = args.length; i < length; i++ ) {
                                elem = args[ i ];
                                type = ReadyObj.type( elem );
                                if ( type === "array" ) {
                                    deferred.done.apply( deferred, elem );
                                } else if ( type === "function" ) {
                                    callbacks.push( elem );
                                }
                            }
                            if ( _fired ) {
                                deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
                            }
                        }
                        return this;
                    },

                    // resolve with given context and args
                    resolveWith: function( context, args ) {
                        if ( !cancelled && !fired && !firing ) {
                            // make sure args are available (#8421)
                            args = args || [];
                            firing = 1;
                            try {
                                while( callbacks[ 0 ] ) {
                                    callbacks.shift().apply( context, args );//shifts a callback, and applies it to document
                                }
                            }
                            finally {
                                fired = [ context, args ];
                                firing = 0;
                            }
                        }
                        return this;
                    },

                    // resolve with this as context and given arguments
                    resolve: function() {
                        deferred.resolveWith( this, arguments );
                        return this;
                    },

                    // Has this deferred been resolved?
                    isResolved: function() {
                        return !!( firing || fired );
                    },

                    // Cancel
                    cancel: function() {
                        cancelled = 1;
                        callbacks = [];
                        return this;
                    }
                };

            return deferred;
        },
        type: function( obj ) {
            return obj == null ?
                String( obj ) :
                class2type[ Object.prototype.toString.call(obj) ] || "object";
        }
    }
    // The DOM ready check for Internet Explorer
    function doScrollCheck() {
        if ( ReadyObj.isReady ) {
            return;
        }

        try {
            // If IE is used, use the trick by Diego Perini
            // http://javascript.nwbox.com/IEContentLoaded/
            document.documentElement.doScroll("left");
        } catch(e) {
            setTimeout( doScrollCheck, 1 );
            return;
        }

        // and execute any waiting functions
        ReadyObj.ready();
    }
    // Cleanup functions for the document ready method
    if ( document.addEventListener ) {
        DOMContentLoaded = function() {
            document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
            ReadyObj.ready();
        };

    } else if ( document.attachEvent ) {
        DOMContentLoaded = function() {
            // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
            if ( document.readyState === "complete" ) {
                document.detachEvent( "onreadystatechange", DOMContentLoaded );
                ReadyObj.ready();
            }
        };
    }
    function ready( fn ) {
        // Attach the listeners
        ReadyObj.bindReady();

        var type = ReadyObj.type( fn );

        // Add the callback
        readyList.done( fn );//readyList is result of _Deferred()
    }
    return ready;
})();

ListonicEventDocumentReady(function() {
	ListonicBlogWidgetInstance.process();
});

